package com.practice.gson;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

import com.google.gson.Gson;

public class GsonSerializer<T> {

	private Gson gson = new Gson();
	
	private Class<T> itemClass;

	public GsonSerializer(Class<T> itemClass) {
		this.itemClass = itemClass;
	}

	public String serialize(T obj) {
		return gson.toJson(obj);
	}

	public T deserialize(String json) {
		return gson.fromJson(json, itemClass);
	}

	/*
	 * public String serialize(T obj) { return gson.toJson(obj); }
	 * 
	 * public T deserialize(String json) { Type type = new TypeToken<T>() {
	 * }.getType();
	 * 
	 * T obj = gson.fromJson(json, type); return obj; }
	 * 
	 * public String serializeList(List<T> personList) { return
	 * gson.toJson(personList); }
	 * 
	 * public List<T> deserializeList(String json) { Type type = new
	 * TypeToken<List<T>>() {
	 * 
	 * }.getType();
	 * 
	 * List<T> personList = gson.fromJson(json, type); return personList; }
	 */
	
	public String serializeList(List<T> list) {
		return gson.toJson(list);
	}
	
	public List<T> deserializeList(String json) {
		Type listType = new ParameterizedType() {
			@Override
			public Type getRawType() {
				
				return List.class;
			}
			@Override
			public Type getOwnerType() {
				
				return null;
			}
			@Override
			public Type[] getActualTypeArguments() {
				Type[] actualTypeArguments = new Type[1];
				actualTypeArguments[0] = itemClass;
				return actualTypeArguments;
			}
		};
		return gson.fromJson(json, listType);
	}
}
